/**
 * Copyright &copy; 2013-2015 山东易科德软件有限公司   All rights reserved.
 */
package cn.net.ecode.modules.gen.service;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.net.ecode.common.persistence.Page;
import cn.net.ecode.common.service.CrudService;
import cn.net.ecode.common.utils.StringUtils;
import cn.net.ecode.modules.gen.dao.GenDataBaseDictDao;
import cn.net.ecode.modules.gen.dao.GenTableColumnDao;
import cn.net.ecode.modules.gen.dao.GenTableDao;
import cn.net.ecode.modules.gen.dao.GenTableJoinDao;
import cn.net.ecode.modules.gen.entity.GenConfig;
import cn.net.ecode.modules.gen.entity.GenTable;
import cn.net.ecode.modules.gen.entity.GenTableColumn;
import cn.net.ecode.modules.gen.entity.GenTableJoin;
import cn.net.ecode.modules.gen.entity.GenTemplate;
import cn.net.ecode.modules.gen.util.GenUtils;

/**
 * 业务表Service
 * @author ThinkGem
 * @version 2014-9-9
 */
@Service
@Transactional(readOnly = true)
public class GenTableService extends CrudService<GenTableDao, GenTable> {

	@Autowired
	private GenTableColumnDao genTableColumnDao;
	@Autowired
	private GenTableJoinDao genTableJoinDao;
	@Autowired
	private GenDataBaseDictDao genDataBaseDictDao;
	
	public GenTable get(String tableName) {
		GenTable genTable = super.get(tableName);
		if (genTable != null){
			genTable.setColumnList(genTableColumnDao.findList(new GenTableColumn(genTable)));
			genTable.setTableJoinList(genTableJoinDao.findList(new GenTableJoin(genTable)));
		}
		return genTable;
	}

	public List<GenTable> findList(GenTable entity) {
		return super.findList(entity);
	}
	
	public Page<GenTable> findPage(Page<GenTable> page, GenTable genTable) {
		return super.findPage(page, genTable);
	}

	/**
	 * 获取物理数据表列表
	 * @param genTable
	 * @return
	 */
	public List<GenTable> findTableListFormDb(GenTable genTable){
		return genDataBaseDictDao.findTableList(genTable);
	}
	
	/**
	 * 验证表名是否可用，如果已存在，则返回false
	 * @param genTable
	 * @return
	 */
	public boolean checkTableName(String tableName){
		if (StringUtils.isBlank(tableName)){
			return true;
		}
		return dao.get(new GenTable(tableName)) == null;
	}
	
	/**
	 * 获取物理数据表列表
	 * @param genTable
	 * @return
	 */
	public GenTable getTableFormDb(GenTable genTable){
		// 如果有表名，则获取物理表
		if (StringUtils.isNotBlank(genTable.getTableName())){
			
			List<GenTable> list = genDataBaseDictDao.findTableList(genTable);
			if (list.size() > 0){
				
				// 如果是新增，初始化表属性
				if (genTable.getIsNewRecord()){
					genTable = list.get(0);
					// 设置字段说明
					if (StringUtils.isBlank(genTable.getComments())){
						genTable.setComments(genTable.getTableName());
					}
					genTable.setClassName(StringUtils.toCapitalizeCamelCase(genTable.getTableName()));
				}
				
				// 添加新列
				List<GenTableColumn> columnList = genDataBaseDictDao.findTableColumnList(genTable);
				for (GenTableColumn column : columnList){
					boolean b = false;
					for (GenTableColumn e : genTable.getColumnList()){
						if (e.getColumnName().equals(column.getColumnName())){
							b = true;
						}
					}
					if (!b){
						genTable.getColumnList().add(column);
					}
				}
				
				// 删除已删除的列
				for (GenTableColumn e : genTable.getColumnList()){
					boolean b = false;
					for (GenTableColumn column : columnList){
						if (column.getColumnName().equals(e.getColumnName())){
							b = true;
						}
					}
					if (!b){
						e.setStatus(GenTableColumn.STATUS_DELETE);
					}
				}
				
				// 获取主键
				genTable.setPkList(genDataBaseDictDao.findTablePK(genTable));
				
				// 初始化列属性字段
				GenUtils.initColumnField(genTable);
				
			}
		}
		return genTable;
	}
	
	@Transactional(readOnly = false)
	public void save(GenTable genTable) {
		super.save(genTable);
		// 保存列
		for (GenTableColumn column : genTable.getColumnList()){
			column.setGenTable(genTable);
			if (StringUtils.isBlank(column.getId())){
				column.preInsert();
				genTableColumnDao.insert(column);
			}else{
				if (GenTableColumn.STATUS_DELETE.equals(column.getStatus())){
					genTableColumnDao.delete(column);
				}else{
					column.preUpdate();
					genTableColumnDao.update(column);
				}
			}
		}
	}
	
	@Transactional(readOnly = false)
	public void delete(GenTable genTable) {
		super.delete(genTable);
		genTableColumnDao.deleteByTableName(new GenTableColumn(genTable));
		genTableJoinDao.deleteByTableName(new GenTableJoin(genTable));
	}
	
	/**
	 * 生成代码
	 * @param genTable
	 * @return
	 */
	public String generateCode(GenTable genTable){

		StringBuilder result = new StringBuilder();
		
		// 获取所有代码模板
		GenConfig config = GenUtils.getConfig();
		
		// 获取模板列表
		List<GenTemplate> templateList = GenUtils.getTemplateList(config, genTable.getTplCategory(), false);
		List<GenTemplate> childTableTemplateList = GenUtils.getTemplateList(config, genTable.getTplCategory(), true);
		
		// 如果有子表模板，则需要获取子表列表
		if (childTableTemplateList.size() > 0){
			GenTable parentTable = new GenTable();
			parentTable.setParent(genTable);
			genTable.setChildList(dao.findList(parentTable));
		}
		
		// 生成子表模板代码
		for (GenTable childTable : genTable.getChildList()){
			childTable.setParent(genTable);
			childTable.setColumnList(genTableColumnDao.findList(new GenTableColumn(childTable)));
			childTable.setTableJoinList(genTableJoinDao.findList(new GenTableJoin(childTable)));
			Map<String, Object> childTableModel = GenUtils.getDataModel(childTable);
			for (GenTemplate tpl : childTableTemplateList){
				result.append(GenUtils.generateToFile(tpl, childTableModel, childTable));
			}
		}
		
		// 生成主表模板代码
		Map<String, Object> model = GenUtils.getDataModel(genTable);
		for (GenTemplate tpl : templateList){
			result.append(GenUtils.generateToFile(tpl, model, genTable));
		}
		return result.toString();
	}
}
